const moment = require('moment');
const { merge } = require('lodash');
const ContractService = require('../service/contract');
const UserService = require('../service/user');
const OrganizationService = require('../service/organization');
const WorkerService = require('../service/worker');
const WorkerSignRecordService = require('../service/workerSignRecordService');
const TenantSignRecordService = require('../service/tenantSignRecordService');
const SettingsService = require('../service/settings');
const tencentcloud = require('tencentcloud-sdk-nodejs');
const EssbasicClient = tencentcloud.essbasic.v20210526.Client;
const contractService = new ContractService();
const userService = new UserService();
const organizationService = new OrganizationService();
const workerService = new WorkerService();
const workerSignRecordService = new WorkerSignRecordService();
const tenantSignRecordService = new TenantSignRecordService();
const settingsService = new SettingsService();

const { v4 } = require('uuid');


const { cloudApiClient, mergeAgent, logger } = require('../utils');

const getAgent = async (req) => {
  const { userInfo } = req;
  const targetUser = userInfo;
  if (!targetUser) {
    console.error('targetUser: not found');
    return false;
  }
  return {
    ...mergeAgent({
      ProxyOrganizationOpenId: targetUser.organizationOpenId,
      OpenId: targetUser.openId,
      ProxyAppId: targetUser.proxyAppId,
    }),
    OrganizationName: targetUser.organizationName,
    UserId: targetUser.userId,
    UserName: targetUser.userName,
  };
};

module.exports = (app) => {
  // 上传文件
  app.post(`${process.env.VUE_APP_BASE_API}/signContractByFile`, async (req, res) => {
    const { body, userInfo } = req;
    const { UserName, UserId, ...agent } = await getAgent(req);

    if (!agent) res.json({ code: 5000, message: 'agent 信息错误' });


    // 域名不一样
    const clientUpload = new EssbasicClient(merge({}, {
      credential: {
        secretId: process.env.VUE_APP_SECRET_ID,
        secretKey: process.env.VUE_APP_SECRET_KEY,
      },
      region: '',
      profile: {
        httpProfile: {
          endpoint: 'essbasic.test.ess.tencent.cn',
        },
      },
    }, {
      profile: {
        httpProfile: {
          endpoint: process.env.FILE_UPDATE_HOST,
        },
      },
    }));

    /**
     * uploadRes @results
     * FileIds	Array of String	文件id数组，有效期一个小时；有效期内此文件id可以反复使用
     * TotalCount	Integer	上传成功文件数量
     * FileUrls	Array of String	文件Url
     * RequestId	String	唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
     * */
    try {
      const uploadRes = await clientUpload.UploadFiles({ Agent: agent, ...body });
      if (!uploadRes.code) {
        const { FileInfos } = body;
        const flowsParams = {
          FlowName: (FileInfos[0] && FileInfos[0].FileName) || `Test-${Math.round(Math.random() * 1000)}`,
          // CallbackUrl: `${process.env.CONTRACT_SIGN_CALLBACK_URL}/api/contractFlows/callback`,
          FlowApprovers: [
            {
              RecipientId: 'xxx',
              OpenId: agent.OpenId,

              // 个人B TO C
              IdCardType: 'ID_CARD',
              IdCardNumber: '',
              Mobile: '',
              ApproveName: UserName,
              ApproverType: 'ORGANIZATION', //

              // 企业
              // OrganizationOpenId: agent.ProxyOrganizationOpenId,
              OrganizationName: agent.OrganizationName,
              // ApproverType: 'ORGANIZATION', // PERSON，ORGANIZATION，ENTERPRISESERVER,PERSON_AUTO_SIGN

              // ？？
              SignComponents: [
                {
                  ComponentId: 'Component1',
                  ComponentType: 'SIGN_SEAL',
                  ComponentRecipientId: 'xxx',
                  ComponentName: '印章',
                  ComponentRequired: true,
                  ComponentHeight: 43,
                  ComponentWidth: 119,
                  ComponentExtra: JSON.stringify({ Date: true, NotSign: true }),
                  ComponentPage: 1,
                },
              ],
            },
          ],
          FileIds: uploadRes.FileIds,
          // SignComponents: [
          //   {
          //     ComponentId: 'Component1',
          //     ComponentType: 'SIGN_SEAL',
          //     ComponentRecipientId: '111',
          //     ComponentName: '印章',
          //     ComponentRequired: true,
          //     ComponentHeight: 43,
          //     ComponentWidth: 119,
          //     ComponentExtra: JSON.stringify({ Date: true, NotSign: true }),
          //     ComponentPage: 1,
          //   },
          //   {
          //     ComponentId: 'Component2',
          //     ComponentType: 'TEXT',
          //     ComponentRecipientId: '222',
          //     ComponentName: '签署人姓名',
          //     ComponentRequired: true,
          //     ComponentHeight: 20,
          //     ComponentWidth: 250,

          //     ComponentExtra: JSON.stringify({
          //       RecipientInfoType: 'PERSONAL-NAME',
          //       FontSize: 12,
          //       FontAlign: 'Left',
          //       Font: '黑体',
          //     }),
          //     ComponentPage: 1,
          //   },
          // ],
          // TODO: 签署时选择
          DeadLine: moment().add(30, 'days')
            .unix(),
        };
        // 创建发起合同流程
        const flowRes = await cloudApiClient.ChannelCreateFlowByFiles({ Agent: agent, ...flowsParams });
        // 查询Flow合同信息
        const flowInfosRes = await cloudApiClient.DescribeFlowDetailInfo({
          Agent: agent,
          FlowIds: [flowRes.FlowId],
        });
        // 存储
        const saveDatas = (flowInfosRes.FlowInfo || []).map(item => ({
          ...item,
          UserId,
          organizationId: userInfo.organizationId,
        }));
        await Promise.all(saveDatas.map(item => contractService.create(item)));
        return res.json({ code: 20000, data: saveDatas });
      }
    } catch (e) {
      console.log(e);
      logger.error({
        error: e,
      });
      res.json({ code: 5000, message: e.message, stack: e.stack });
    }
  });

  app.post(`${process.env.VUE_APP_BASE_API}/createSignUrl`, async (req, res) => {
    const { FlowId } = req.body;
    const { UserName, UserId, ...agent } = await getAgent(req);
    // console.log(FlowId, '888888888');
    cloudApiClient
      .CreateSignUrls({
        FlowIds: [FlowId],
        Endpoint: 'WEIXINAPP',
        GenerateType: 'CHANNEL',
        OrganizationOpenId: agent.ProxyOrganizationOpenId,
        // OpenId: agent.ProxyAppId,
        Agent: agent,
      })
      .then(
        (data) => {
          console.log(data);
          return res.json({ code: 20000, data });
        },
        (err) => {
          console.log('error：', err);
          res.json({ code: 5000, message: err.code });
        },
      );
  });
  // 模板批量创建签署流程
  app.post(`${process.env.VUE_APP_BASE_API}/template/CreateFlowsByTemplates`, async (req, res) => {
    const { body, userInfo } = req;
    const { UserName, UserId, ...agent } = await getAgent(req);
    if (agent) {
      const params = {
        Agent: agent,
        Version: '2021-05-26',
        ...body,
      };

      // 增加回调地址
      // params.FlowInfos = (params.FlowInfos || []).map(item => ({
      //   ...item,
      //   CallbackUrl: `${process.env.CONTRACT_SIGN_CALLBACK_URL}/api/contractFlows/callback`,
      // }));

      const flowRes = await cloudApiClient.CreateFlowsByTemplates(params);

      if (flowRes.ErrorMessages && flowRes.ErrorMessages.length && flowRes.ErrorMessages[0]) {
        return res.json({
          code: 50000,
          message: flowRes.ErrorMessages.join(','),
        });
      }

      if (flowRes && flowRes.FlowIds) {
        // save to contract
        const flowInfosRes = await cloudApiClient.DescribeFlowDetailInfo({
          Agent: agent,
          FlowIds: flowRes.FlowIds || [],
        });

        // 存储
        const saveDatas = (flowInfosRes.FlowInfo || []).map(item => ({
          ...item,
          UserId,
          organizationId: userInfo.organizationId,
        }));
        // contractService.create(saveData);
        await Promise.all(saveDatas.map(item => contractService.create(item)));
        return res.json({ code: 20000, data: saveDatas });
      }

      res.json({
        code: 500,
      });
    }
  });

  app.post(`${process.env.VUE_APP_BASE_API}/describeFlowDetailInfo`, async (req, res) => {
    const { flowId } = req.body;
    const { UserName, UserId, ...agent } = await getAgent(req);
    try {
      const flowInfosRes = await cloudApiClient.DescribeFlowDetailInfo({
        Agent: agent,
        FlowIds: [flowId],
      });
      res.status(200).json({
        code: 20000,
        data: flowInfosRes,
      });
    } catch (err) {
      res.json({
        code: 50000,
        message: err.code,
      });
    }
  });

  // 渠道版撤销签署流程 ChannelCancelFlow
  app.post(`${process.env.VUE_APP_BASE_API}/channelCancelFlow`, async (req, res) => {
    const { userInfo, body } = req;
    const targetUser = userInfo;
    if (targetUser) {
      const params = {
        Agent: mergeAgent({
          ProxyOrganizationOpenId: targetUser.organizationOpenId,
          OpenId: targetUser.openId,
          ProxyAppId: targetUser?.proxyAppId,
        }),
        Version: '2021-05-26',
        ...body,
      };
      cloudApiClient
        .ChannelCancelFlow(params)
        .then(
          (data) => {
            res.json({
              code: 20000,
              data,
            });
          },
          (err) => {
            // console.log('err====', err);
            res.json(err);
          },
        )
        .catch((error) => {
          console.log('error====', error);
        });
    } else {
      res.json({
        code: 500,
      });
    }
  });

  // 合同列表
  app.post(`${process.env.VUE_APP_BASE_API}/contractFlows/list`, async (req, res) => {
    const { userInfo, body } = req;
    const { limit = 10, offset = 0, contractType = 0, contractName = '', contractId = '', contractStatus = '' } = body;
    const targetUser = userInfo;
    if (targetUser) {
      const params = {
        flowId: contractId,
        flowStatus: contractStatus,
        organizationId: targetUser.organizationId,
        flowName: contractName,
        limit,
        offset,
      };
      if (contractType === 1) { // 劳务派遣合同
        const contracts = await contractService.searchWithTenants(params);
        const count = await contractService.countWithTenants(params);
        return res.json({
          code: 20000,
          data: { contracts, totalCount: count },
        });
      } if (contractType === 2) { // 劳务合同
        const contracts = await contractService.searchWithWorkers(params);
        const count = await contractService.countWithWorkers(params);
        return res.json({
          code: 20000,
          data: { contracts, totalCount: count },
        });
      }
      const contracts = await contractService.search({
        organizationId: targetUser.organizationId,
        limit,
        offset,
      });
      const count = await contractService.searchCount({
        organizationId: targetUser.organizationId,
      });
      return res.json({
        code: 20000,
        data: { contracts, totalCount: count },
      });
    }
    return res.json({
      code: 50204,
      message: '用户登录已过期，请退出重试',
    });
  });

  app.post(`${process.env.VUE_APP_BASE_API}/contractFlows/callback`, async (req, res) => {
    const { body = {} } = req;

    const msgData = body.MsgData || {};
    logger.info({
      ...req.body,
      Action: 'contractFlows/callback',
    });


    const flowId = msgData.FlowId;

    if (flowId) {
      // update status
      const contractItem = await contractService.first({ FlowId: flowId });
      if (contractItem) {
        // return targetUser
        // contractService.update()
        res.json({ data: contractItem, code: 20000 });
        return;
      }
    }
    res.json({});
  });

  app.get(`${process.env.VUE_APP_BASE_API}/contractFlows/:flowId`, async (req, res) => {
    const { params = {} } = req;
    const targetUser = await contractService.first({ FlowId: params.flowId });
    if (targetUser) {
      // return targetUser
      res.json({ data: targetUser, code: 20000 });
      return;
    }
    res.json({
      code: 50204,
      message: '用户不存在',
    });
  });

  app.post(`${process.env.VUE_APP_BASE_API}/contractFlow`, async (req, res) => {
    const { body } = req;
    try {
      if (!body.FlowId) {
        return res.status(400).json({
          code: 40000,
          message: 'FlowId 不存在',
        });
      }
      const item = await contractService.update(body.FlowId, body);
      return res.status(200).json({
        code: 20000,
        data: item,
      });
    } catch (err) {
      res.status(500).json({
        code: 500,
        stack: err.stack,
        message: err.message,
      });
    }
  });

  app.get(`${process.env.VUE_APP_BASE_API}/contractFlow/:flowId`, async (req, res) => {
    const { params = {} } = req;
    const { flowId } = params;
    try {
      if (!flowId) {
        return res.status(400).json({
          code: 40000,
          message: 'FlowId 不存在',
        });
      }
      const item = await contractService.first({ FlowId: flowId });
      return res.status(200).json({
        code: 20000,
        data: item,
      });
    } catch (err) {
      res.status(500).json({
        code: 500,
        stack: err.stack,
        message: err.message,
      });
    }
  });

  // h5合同列表
  app.post(`${process.env.VUE_APP_M_BASE_API}/contracts/list`, async (req, res) => {
    try {
      const { userInfo, body } = req;
      const { limit = 10, offset = 0, contractType = 0, status = '' } = body;
      const targetUser = userInfo;
      if (targetUser) {
        const params = {
          organizationId: targetUser.organizationId,
          flowStatus: status,
          contractType,
          limit,
          offset,
          workerId: userInfo.id,
        };
        if (contractType === 2) {
          const contracts = await contractService.searchWithWorkersByMobile(params);
          const count = await contractService.countWithWorkersByMobile(params);
          if (status) {
            // h5签署列表需根据签署人状态特殊处理下合同待签署和签署中的状态
            // 待签署-展示C端客户未签署的情况
            // 签署中-展示C端客户已签署 B端企业未签署情况
            let filterContracts = [...contracts];
            if (status === 'WAITSIGN') { // 待签署
              filterContracts = filterContracts.filter(f => ['FILLPENDING', 'PENDING'].includes(JSON.parse(f.FlowApproverInfos)?.[1]?.ApproveStatus));
            }
            if (status === 'PART') { // 签署中
              filterContracts = filterContracts.filter(f => ['FILLPENDING', 'PENDING'].includes(JSON.parse(f.FlowApproverInfos)?.[0]?.ApproveStatus) && JSON.parse(f.FlowApproverInfos)?.[1]?.ApproveStatus === 'ACCEPT');
            }
            return res.json({
              code: 20000,
              data: { contracts: filterContracts, totalCount: filterContracts.length },
            });
          }
          return res.json({
            code: 20000,
            data: { contracts, totalCount: count },
          });
        }
        return res.json({
          code: 20000,
          data: { contracts: [], totalCount: 0 },
        });
      }
      return res.json({
        code: 50204,
        message: '用户登录已过期，请退出重试',
      });
    } catch (error) {
      console.error(error);
      res.json({
        code: 50000,
        ...error,
        message: error.message,
      });
    }
  });

  app.post(`${process.env.VUE_APP_M_BASE_API}/contracts/createSignUrl`, async (req, res) => {
    try {
      const { userInfo, body } = req;
      const { flowId } = body;
      const adminUser = await userService.first({ verified: true, organizationId: userInfo.organizationId });
      const org = await organizationService.find(userInfo.organizationId);
      if (adminUser) {
        const signResult = await cloudApiClient.request('ChannelCreateFlowSignUrl', {
          Agent: mergeAgent({
            ProxyOrganizationOpenId: org.organizationId,
            OpenId: adminUser.openId,
            ProxyAppId: org.proxyAppId,
          }),
          FlowId: flowId,
          FlowApproverInfos: [
            {
              ApproverType: 'PERSON',
              Mobile: userInfo.mobile,
              Name: userInfo.name,
            },
          ],
        });

        res.json({
          code: 20000,
          data: signResult,
          message: 'ok',
        });
        return;
      }
      res.json({
        code: 50000,
        message: '未查询到经办人',
      });
    } catch (err) {
      console.error(err);
      res.json({
        code: 50000,
        ...err,
        message: err.message,
        stack: err.stack,
      });
    }
  });


  app.post(`${process.env.VUE_APP_M_BASE_API}/contracts/getFlowResourceUrls`, async (req, res) => {
    try {
      const { userInfo, body } = req;
      const { flowId } = body;
      const adminUser = await userService.first({ verified: true, organizationId: userInfo.organizationId });
      const org = await organizationService.find(userInfo.organizationId);
      if (adminUser) {
        const signResult = await cloudApiClient.DescribeResourceUrlsByFlows({
          Agent: mergeAgent({
            ProxyOrganizationOpenId: org.organizationId,
            OpenId: adminUser.openId,
            ProxyAppId: org.proxyAppId,
          }),
          FlowIds: [flowId],
        });

        res.json({
          code: 20000,
          data: signResult,
          message: 'ok',
        });
        return;
      }
      res.json({
        code: 50000,
        message: '未查询到经办人',
      });
    } catch (err) {
      console.error(err);
      res.json({
        code: 50000,
        ...err,
        message: err.message,
        stack: err.stack,
      });
    }
  });
  app.post(`${process.env.VUE_APP_BASE_API}/contracts/createSingleSign`, async (req, res) => {
    const { body, userInfo } = req;
    const { UserName, UserId, ...agent } = await getAgent(req);
    const { signType = 'singleB', tenantId } = body;

    if (agent) {
      const params = {
        Agent: agent,
        Version: '2021-05-26',
        ...body,
      };
      try {
        const flowRes = await cloudApiClient.CreateFlowsByTemplates(params);

        if (flowRes.ErrorMessages && flowRes.ErrorMessages.length && flowRes.ErrorMessages[0]) {
          logger.error({
            action: 'contracts/createSingleSign',
            data: body,
            errMessage: flowRes.ErrorMessages,
          });
          return res.json({
            code: 50000,
            message: flowRes.ErrorMessages.join(','),
          });
        }
        if (flowRes && flowRes.FlowIds) {
          // save to contract
          const flowInfosRes = await cloudApiClient.DescribeFlowDetailInfo({
            Agent: agent,
            FlowIds: flowRes.FlowIds || [],
          });

          // 存储 合同数据
          const saveDatas = (flowInfosRes.FlowInfo || []).map(item => ({
            ...item,
            UserId,
            organizationId: userInfo.organizationId,
          }));
          // 存储合同信息
          await Promise.all(saveDatas.map(item => contractService.create(item)));
          if (signType === 'singleC') {
            // 存储员工签署合同记录
            await Promise.all(
              saveDatas.map((item, idx) =>
                workerSignRecordService.create({
                  id: v4(),
                  contractId: item.FlowId,
                  workerId: params.FlowInfos[idx].FlowApprovers[0].WorkerId,
                  status: 'INIT',
                  type: 'work-contract',
                }),
              ),
            );
            return res.json({ code: 20000, data: saveDatas });
          } if (signType === 'singleB') {
            // 存储员工签署合同记录
            const tempFlowid = flowRes?.FlowIds?.[0];
            // save 用工单位签署合同记录
            const tenantRecordData = await tenantSignRecordService.create({
              contractId: tempFlowid,
              tenantId,
              status: 'INIT',
              userId: userInfo.userId,
            });
            return res.json({ code: 20000, data: [tenantRecordData] });
          }
        }
      } catch (error) {
        console.log('error:', error);
        return res.json({
          code: 500,
          message: error.message,
          requestId: error.requestId,
        });
      }
    }
  });
  // 移动端签署链接
  async function createMobileSignUrl(flowId, userInfo) {
    try {
      const adminUser = await userService.first({ verified: true, organizationId: userInfo.organizationId });
      const org = await organizationService.find(userInfo.organizationId);
      if (adminUser) {
        const signResult = await cloudApiClient.request('ChannelCreateFlowSignUrl', {
          Agent: mergeAgent({
            ProxyOrganizationOpenId: org.organizationId,
            OpenId: adminUser.openId,
            ProxyAppId: org.proxyAppId,
          }),
          FlowId: flowId,
          FlowApproverInfos: [
            {
              ApproverType: 'PERSON',
              Mobile: userInfo.mobile,
              Name: userInfo.name,
            },
          ],
        });

        return signResult;
      }
      return '';
    } catch (err) {
      return '';
    }
  }
  // 移动端单C签署---签署信息处理
  function handleSingleCFlowInfos(template, userInfo) {
    const personArr = template?.Recipients?.filter(f => f.RecipientType === 'INDIVIDUAL');
    const serverTime = +new Date();
    return [{
      FlowName: `${userInfo.name}的安全承诺书`,
      Deadline: Math.ceil(+new Date(serverTime + 30 * 24 * 3600 * 1000) / 1000),
      TemplateId: template.TemplateId,
      FlowApprovers: [{
        ApproverType: 'PERSON',
        RecipientId: personArr[0]?.RecipientId,
        Name: userInfo.name,
        Mobile: userInfo.mobile,
        WorkerId: userInfo.id,
        JumpUrl: 'https://channel-demo.test.ess.tencent.cn/m',
      }],
    }];
  }

  app.post(`${process.env.VUE_APP_M_BASE_API}/contracts/createSingleSign`, async (req, res) => {
    const { body, userInfo } = req;
    const { signType = 'singleC', NeedPreview, PreviewType } = body;

    const adminUser = await userService.first({ verified: true, organizationId: userInfo.organizationId });

    const orgSettings = await settingsService.first({ organizationId: userInfo.organizationId });
    let safeDealTpl = '';
    if (orgSettings?.safeDealTpl) {
      safeDealTpl = orgSettings.safeDealTpl;
    } else {
      return res.json({
        code: 500,
        message: '请联系管理员配置安全承诺书模版',
      });
    }

    const org = await organizationService.find(userInfo.organizationId);
    const agent = mergeAgent({
      ProxyOrganizationOpenId: org.organizationId,
      OpenId: adminUser.openId,
      ProxyAppId: org.proxyAppId,
    });

    if (agent) {
      try {
        const templateRes = await cloudApiClient.DescribeTemplates({
          Agent: agent,
          Version: '2021-05-26',
          TemplateId: safeDealTpl,
        });
        const flowInfos = handleSingleCFlowInfos(templateRes.Templates?.[0], userInfo);
        const flowRes = await cloudApiClient.CreateFlowsByTemplates({
          Agent: agent,
          Version: '2021-05-26',
          FlowInfos: flowInfos,
          NeedPreview,
          PreviewType,
        });
        console.log('NeedPreview:', NeedPreview, flowRes);
        if (flowRes.ErrorMessages && flowRes.ErrorMessages.length && flowRes.ErrorMessages[0]) {
          logger.error({
            action: 'contracts/createSingleSign',
            data: body,
            errMessage: flowRes.ErrorMessages,
          });
          return res.json({
            code: 50000,
            message: flowRes.ErrorMessages.join(','),
          });
        }
        if (NeedPreview && flowRes?.PreviewUrls?.length) {
          return res.json({
            code: 20000,
            previewUrl: flowRes?.PreviewUrls?.[0],
          });
        }
        if (flowRes && flowRes.FlowIds) {
          // save to contract
          const flowInfosRes = await cloudApiClient.DescribeFlowDetailInfo({
            Agent: agent,
            FlowIds: flowRes.FlowIds || [],
          });

          // 存储 合同数据
          const saveDatas = (flowInfosRes.FlowInfo || []).map(item => ({
            ...item,
          }));
          // 存储合同信息
          await Promise.all(saveDatas.map(item => contractService.create({
            ...item,
            FlowApproverInfos: JSON.stringify(item.FlowApproverInfos),
            type: 'safe-proposal',
            organizationId: userInfo.organizationId,
          })));
          if (signType === 'singleC') {
            // 存储员工签署合同记录
            await Promise.all(
              [workerSignRecordService.create({
                id: v4(),
                contractId: saveDatas?.[0]?.FlowId,
                workerId: userInfo.id,
                status: 'INIT',
                type: 'safe-proposal',
              }),
              workerService.update(userInfo.id, {
                proposalStatus: 'INIT', // 更新工人的安全承诺书签署状态
              }),
              ],
            );
            const signRes = await createMobileSignUrl(saveDatas?.[0]?.FlowId, userInfo);

            if (signRes && signRes.FlowApproverUrlInfos?.length) {
              return res.json({
                code: 20000,
                data: signRes.FlowApproverUrlInfos[0],
              });
            }
            return res.json({ code: 500, message: '生成签署链接失败' });
          }
          // if (signType === 'singleB') {
          //   // 存储员工签署合同记录
          //   const tempFlowid = flowRes?.FlowIds?.[0];
          //   // save 用工单位签署合同记录
          //   const tenantRecordData = await tenantSignRecordService.create({
          //     contractId: tempFlowid,
          //     tenantId,
          //     status: 'INIT',
          //     userId: userInfo.userId,
          //   });
          //   return res.json({ code: 20000, data: [tenantRecordData] });
          // }
        }
      } catch (error) {
        return res.json({
          code: 500,
          message: error.message,
          requestId: error.requestId,
        });
      }
    }
  });

  // 合同(批量)下载链接
  app.post(`${process.env.VUE_APP_BASE_API}/contractFlows/download`, async (req, res) => {
    const { body } = req;
    const { UserName, UserId, ...agent } = await getAgent(req);
    if (agent) {
      try {
        const params = {
          Agent: agent,
          Version: '2021-05-26',
          FlowIds: body.flowIds,
        };
        // console.log('params===', params);
        const downloadRes = await cloudApiClient.DescribeResourceUrlsByFlows(params);
        if (downloadRes?.ErrorMessages?.[0]) {
          return res.json({
            code: 50000,
            message: downloadRes.ErrorMessages.join(','),
          });
        }
        if (downloadRes?.FlowResourceUrlInfos?.length) {
          return res.json({ code: 20000, data: downloadRes });
        }
        return res.json({
          code: 50204,
          message: '下载失败',
        });
      } catch (error) {
        console.log('error====', error);
        logger.error({
          action: 'contractFlows/download',
          data: body,
          errMessage: error,
        });
        return res.json({
          code: 500,
          message: error.message,
          requestId: error.requestId,
        });
      }
    }
    return res.json({
      code: 50204,
      message: '用户登录已过期，请退出重试',
    });
  });
};
